package com.gzz.socket.aio.time;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.Date;

/**
 *
 */
public class ServerReadCompletionHandler implements CompletionHandler<Integer, ByteBuffer> {
    private AsynchronousSocketChannel channel;

    public ServerReadCompletionHandler(AsynchronousSocketChannel channel){
        this.channel = channel;
    }

    @Override
    public void completed(Integer result, ByteBuffer attachment) {
        // 首先对attachment进行flip操作，为后续的缓冲区读取数据作准备
        // 根据缓冲区的可读字节数创建byte数组，然后通过new String()方法创建请求信息，对消息进行判断。
        // 如果是“Query time Order”则获取当前服务端系统时间，调用doWrite方法发送给客户端。
        attachment.flip();
        byte[] body = new byte[attachment.remaining()];
        attachment.get(body);
        try {
            String req = new String(body, "UTF-8");
            System.out.println("The time server receive order: " + req);
            String currentTime = "Query time Order".equalsIgnoreCase(req) ?
                    new Date(System.currentTimeMillis()).toString() : "BAD ORDER";
            doWrite(currentTime);
        } catch (UnsupportedEncodingException e) {

        }
    }

    private void doWrite(String currentTime) {
        //首先对当前系统时间合法性检验，如果合法，调用字符串的解码方法将应答消息编码成字节组，
        // 然后将他复制到发送缓冲区buffer中，最后调用AsynchronousServerSocketChannel的异步方法write。
        if (currentTime != null && currentTime.trim().length() > 0) {
            byte[] bytes = currentTime.getBytes();
            ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
            buffer.put(bytes);
            buffer.flip();
            //
            channel.write(buffer, buffer, new CompletionHandler<Integer, ByteBuffer>() {
                @Override
                public void completed(Integer result, ByteBuffer attachment) {
                    // 如果没有发送完成，继续发送
                    // 对发送的buffer进行判断，如果还有剩余的字节可写，说明没有发送完成，需要继续发送，直到发送成功
                    if(attachment.hasRemaining()){
                        channel.write(buffer,buffer, this);
                    }
                }

                //当发生异常的时候，对异常Throwable进行判断：如果是I/O异常，就关闭链路，释放资源；
                //如果是其他异常，按照业务自己的逻辑进行处理。
                @Override
                public void failed(Throwable exc, ByteBuffer attachment) {
                    try {
                        channel.close();
                    } catch (IOException e){
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    @Override
    public void failed(Throwable exc, ByteBuffer attachment) {
        try {
            this.channel.close();
        } catch (IOException e){
            e.printStackTrace();
        }

    }
}
